package com.sofwin;/**
 * @PackageName:com.sofwin
 * @author:andyLiu
 * @DateTime:2020/12/31 14:25
 * @Description:[TODO]输入当前模块作用
 **/

import com.sofwin.mapper.SRoleresourceMapper;
import com.sofwin.pojo.SUser;
import com.sofwin.service.ResourceService;
import com.sofwin.service.UserService;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.realm.Realm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.List;

/**
 * @ClassName: UserReal
 * @Description: TODO
 * @Author: andyliu
 * @Date: 2020/12/31 14:25
 * @Version: 1.0
 **/
@Component
public class UserRealm extends AuthorizingRealm {
    @Autowired
    UserService userService;
    @Autowired
    ResourceService resourceService;
    /**
     * 授权
     * @param principalCollection
     * @return
     */
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
       // 获取当前主体
        Object primaryPrincipal =principalCollection.getPrimaryPrincipal();
        String userName = primaryPrincipal.toString();// 用户名
        SUser user = new SUser();
        user.setLoginAccount(userName);
        SUser sUser = userService.selectUserByLoginAccount(user);
        Integer roleId = sUser.getRoleid();
        //
        SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
        // 根据角色id查询该角色的3级资源
        List<String> permissions= resourceService.selectRolePermission(roleId);
        info.addStringPermissions(permissions);

        return info;
    }

    /**
     * 认证方法
     * @param authenticationToken
     * @return
     * @throws AuthenticationException
     */
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        // 可以获取到subject中的用户名和密码
        UsernamePasswordToken token =(UsernamePasswordToken)authenticationToken;
        String userName = token.getUsername();
        String pwd = new String(token.getPassword());
        SUser user = new SUser();
        user.setLoginAccount(userName);
        SUser sUser = userService.selectUserByLoginAccount(user);
        if(sUser==null){
            throw new UnknownAccountException();
        }
        if(!sUser.getPwd().equals(pwd)){
            throw new IncorrectCredentialsException();
        }
        SimpleAuthenticationInfo info = new SimpleAuthenticationInfo(userName,pwd,sUser.getRealName());
        return info;
    }
}
